<template>
  <div class="upload">
    <!-- :before-upload="handleBeforeUpload" -->
    <el-upload
      multiple
      action="xxxx"
      :on-error="handleUploadError"
      :file-list="fileList"
      :show-file-list="true"
      ref="fileUpload"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <!-- <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件，且不超过500kb
      </div> -->
    </el-upload>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      // 文件上传地址
      url: "",
      fileList: [],
      uploadList: [],
      // 数量限制
      limit: {
        type: Number,
        default: 5,
      },
    };
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          // this.$modal.msgError(
          //   `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          // );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          // this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 上传失败
    handleUploadError(err) {
      // this.$modal.msgError("上传文件失败，请重试");
      // this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log(res);
      if (res.code === 0) {
        this.uploadList.push({ name: res.data.name, url: res.data.src });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        // this.$modal.closeLoading();
        // this.$modal.msgError(res.errmsg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        // this.$modal.closeLoading();
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
  },
  created() {},
  mounted() {},
};
</script>

<style lang="scss" scoped>
.upload {
  text-align: center;
}
</style>
